package quercus;

import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.Writer;

import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptException;
import javax.script.SimpleBindings;

import com.caucho.quercus.QuercusContext;
import com.caucho.quercus.QuercusExitException;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.page.InterpretedPage;
import com.caucho.quercus.page.QuercusPage;
import com.caucho.quercus.parser.QuercusParser;
import com.caucho.quercus.program.QuercusProgram;
import com.caucho.vfs.NullWriteStream;
import com.caucho.vfs.ReadStream;
import com.caucho.vfs.ReaderStream;
import com.caucho.vfs.ReaderWriterStream;
import com.caucho.vfs.WriteStream;

/**
 * Script engine
 */
@SuppressWarnings("serial")
public class MondayScriptingEngine extends AbstractScriptEngine implements
		Compilable, Serializable {
	private MondayScriptingFactory _factory;
	private final MondayScriptingContext _quercus;

	MondayScriptingEngine(MondayScriptingFactory factory) {
		this(factory, createContext());
	}

	public MondayScriptingEngine(MondayScriptingFactory factory,
			MondayScriptingContext quercus) {
		_factory = factory;
		_quercus = quercus;

	}

	private static MondayScriptingContext createContext() {
		MondayScriptingContext context = new MondayScriptingContext();
		context.setUnicodeSemantics(true);
		context.init();
		context.start();

		return context;
	}

	/**
	 * Returns the Quercus object. php/214h
	 */
	public QuercusContext getQuercus() {
		return _quercus;
	}

	/**
	 * run based on a reader.
	 */
	public Object run(String script) throws ScriptException {
		Env env = null;
		ScriptContext cxt = this.getContext();
		try {
			ReadStream reader = com.caucho.vfs.StringReader.open(script);
			reader.setEncoding("utf-8");
			QuercusProgram program = QuercusParser
					.parse(_quercus, null, reader);
			Writer writer = cxt.getWriter();
			WriteStream out;

			if (writer != null) {

				ReaderWriterStream s = new ReaderWriterStream(null, writer);
				WriteStream os = new WriteStream(s);

				os.setNewlineString("\n");

				try {
					os.setEncoding("utf-8");
				} catch (Exception e) {
					e.printStackTrace();
				}

				out = os;
			} else {
				out = new NullWriteStream();
				System.out.println("NullWriteStream");
			}

			QuercusPage page = new InterpretedPage(program);

			env = new Env(_quercus, page, out, null, null);

			env.setScriptContext(cxt);

			// php/214c
			env.start();

			Object result = null;

			try {
				Value value = program.execute(env);

				if (value != null)
					result = value.toJavaObject();
			} catch (QuercusExitException e) {
				e.printStackTrace();
			}

			out.flushBuffer();
			out.free();

			// flush buffer just in case
			//
			// jrunscript in interactive mode does not automatically flush its
			// buffers after every input, so output to stdout will not be seen
			// until the output buffer is full
			//
			// http://bugs.caucho.com/view.php?id=1914
			writer.flush();

			return result;

			/*
			 * } catch (ScriptException e) { throw e;
			 */
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new ScriptException(e);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			if (env != null)
				env.close();
		}
	}

	/**
	 * evaluates based on a script.
	 */
	public Object eval(String script, ScriptContext cxt) throws ScriptException {
		return eval(new StringReader(script), cxt);
	}

	/**
	 * evaluates based on a script.
	 */
	public MondayCompiledScript compile(String script) throws ScriptException {
		try {			
			ReadStream reader = com.caucho.vfs.StringReader.open(script);
			reader.setEncoding("utf-8");
			QuercusProgram program = QuercusParser
					.parse(_quercus, null, reader);			
			return new MondayCompiledScript(this, program);
		} catch (Exception ex) {
			ex.printStackTrace();
		}		
		return null;
	}

	/**
	 * Returns the engine's factory.
	 */
	public MondayScriptingFactory getFactory() {
		return _factory;

	}

	/**
	 * Creates a bindings.
	 */
	public Bindings createBindings() {
		return new SimpleBindings();
	}

	public String toString() {
		return "QuercusScriptEngine[]";
	}

	public CompiledScript compile(Reader script) throws ScriptException {
		try {
			ReadStream reader = ReaderStream.open(script);

			QuercusProgram program = QuercusParser
					.parse(_quercus, null, reader);

			return new MondayCompiledScript(this, program);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new ScriptException(e);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Object eval(Reader reader, ScriptContext context)
			throws ScriptException {
		// TODO Auto-generated method stub
		return null;
	}
}
